(function() {
	'use strict';
	var sc = angular.module('sc', [ 'localytics.directives', 'ui.router', 'ngSanitize', 'frapontillo.bootstrap-switch', 'toaster',
			'ngAnimate' ])
	modalService.$inject = [ '$q', '$rootScope', '$compile', '$sce', '$http' ]
	function modalService($q, $rootScope, $compile, $sce, $http) {
		var modalTemplate;
		$http.get(':sc:template/modalTpl.html').success(function(r) {
			modalTemplate = r;
		})
		var alertTemplate = '<span></span>'
		var succ = 'text-success';
		var warn = 'text-warning';
		var error = 'text-danger';
		function provider() {
			var remodal
			var e
			this.create = function(element, options) {
				e = element
				remodal = $(element).remodal(options)
				e.on('closing', function() {
					remodal.destroy()
				})
			}
			this.close = function() {
				remodal.close()
			}
			this.destroy = function() {
				remodal.close()
			}
			this.show = function() {
				remodal.open()
			}
			this.onShown = function(fn) {
				e.on('opened', fn)
			}
			this.onClose = function(fn) {
				e.on('closed', fn)
			}
			return this;
		}
		this.confirm = function(param, option) {
			var q = $q.defer();
			var p = {
				title : '提示',
				titleCls : succ,
				content : '',
				result : '',
				size : 'md',
				isConfirm : true
			}
			if (angular.isObject(param)) {
				angular.extend(p, param)
			} else {
				p.content = param;
			}
			var $scope = $rootScope.$new();
			var element, form, validate
			angular.extend($scope, p)
			var modal = new provider()
			$scope.confirm = function() {
				if (p.validator) {
					var r = p.validator($scope.result)
					if (r != undefined) {
						if (r == false) {
							return;
						}
						if (r.then) {
							r.then(function() {
								q.resolve($scope.result);
								modal.destroy()
							})
							return;
						}
					}
				}
				if (form.length != 0) {
					if (validate.form()) {
						q.resolve($scope.result);
						modal.destroy()
					}
				} else {
					q.resolve($scope.result);
					modal.destroy()
				}
			}
			$scope.cancel = function() {
				q.reject();
				modal.destroy()
				return true;
			}
			element = $compile(modalTemplate)($scope);
			$scope.$$phase || $scope.$apply();
			modal.create(element, option = option || 'show')
			modal.onClose(function() {
				q.reject();
				modal.destroy()
			})
			modal.onShown(function() {
				q.notify(element);
				form = element.find('form')
				if (form.length > 0) {
					require([ 'jquery-validate-locale' ], function() {
						validate = form.validate()
					})
				}
			})

			modal.show()
			if (p.duration) {
				setTimeout(function() {
					modal.destroy()
				}, p.duration);
			}
			q.promise.close = function() {
				modal.destroy()
			}
			return q.promise;
		}
		this.show = function(param, option) {
			var p = {
				title : '提示',
				titleCls : succ,
				content : '',
				size : 'md',
				isConfirm : false
			};
			angular.extend(p, param)
			return this.confirm(p, option);
		}
		this.warn = function(content, duration) {
			return this.show({
				content : content,
				titleCls : warn,
				size : 'sm',
				duration : duration
			})
		}
		this.succ = function(content, duration) {
			return this.show({
				content : content,
				titleCls : succ,
				size : 'sm',
				duration : duration
			})
		}
		this.error = function(content, duration) {
			return this.show({
				content : content,
				titleCls : error,
				size : 'sm',
				duration : duration
			})
		}
		return this;
	}
	sc.factory('modalService', modalService)

	ngHtmlDirective.$inject = [ '$parse', '$compile' ];
	function ngHtmlDirective($parse, $compile) {
		return {
			restrict : 'A',
			priority : 999,
			link : function(scope, element, attr) {
				var parsed = $parse(attr.ngHtml);
				var old;
				function getValue() {
					try {
						return parsed(scope);
					} catch (e) {
						return scope[attr.ngHtml];
					}
				}
				scope.$watch(getValue, function ngBindHtmlWatchAction(value) {
					if (old == value) {
						return;
					}
					old = value;
					element.html(value);
					$compile(element.contents())(scope);
				});
			}
		}
	}
	sc.directive('ngHtml', ngHtmlDirective)
	$.event.special.destroyed = {
		remove : function(o) {
			if (o.handler) {
				o.handler()
			}
		}
	}
	sc.directive('datepicker', function() {
		return {
			restrict : 'A',
			require : [ '?ngModel' ],
			link : function(scope, element, attr, ctrls) {
				var nullText = attr.nullText, current
				var ngModelCtrl = ctrls[0]
				require([ 'jquery-datepicker-locale' ], function() {
					element.datepicker($.datepicker.regional['zh-CN']);
					var altFormat = element.datepicker("option", "dateFormat");
					$('#ui-datepicker-div').hide()

					if (ngModelCtrl) {
						ngModelCtrl.$parsers.push(function(input) {
							if (input) {
								return element.datepicker('getDate').getTime();
							} else {
								return input;
							}
						})
						current && element.datepicker('setDate', new Date(current));
					}
				})
				ngModelCtrl.$formatters.push(function(input) {
					if (input) {
						current = input
						setTimeout(function() {
							element.datepicker && element.datepicker('setDate', new Date(input));
						})
					}
					return nullText ? nullText : input;
				})
			}
		}
	})
	function UMeditorDirective() {
		return {
			restrict : 'A',
			require : [ '?ngModel' ],
			link : function(scope, element, attr, ctrls) {
				var clone = element.clone();
				element.hide()
				element.after(clone)
				UM.clearCache(clone[0])
				var ue = UM.getEditor(clone[0], {
					initialFrameHeight : '100%',
					topOffset : 45,
					zIndex : 1029,
					initialContent : ''
				});
				scope.ue = ue
				clone.on('destroyed', function() {
					ue.destroy()
				})
				var ngModelCtrl = ctrls[0]
				var current = '';
				if (ngModelCtrl) {
					ngModelCtrl.$formatters.push(function(input) {
						if (input) {
							setTimeout(function() {
								ue.setContent && ue.setContent(input)
							})
							current = input
						}

						return input;
					})
					ue.ready(function() {
						ue.body.form = element.parents('form')
						ue.$container.keyup(function() {
							ngModelCtrl.$setViewValue(ue.getContent())
						})
						ue.setContent(current)
					})
				}

			}
		}
	}
	function UEditorDirective() {
		return {
			restrict : 'A',
			require : [ '?ngModel' ],
			link : function(scope, element, attr, ctrls) {
				var ngModelCtrl = ctrls[0]
				var current = '';
				if (ngModelCtrl) {
					ngModelCtrl.$formatters.push(function(input) {
						if (input) {
							current = input
						}
						return input;
					})
				}
				require([ 'ueditor', 'zeroClipboard' ], function(UE, zeroClipboard) {
					window.ZeroClipboard = zeroClipboard;
					UE.delEditor(element[0])
					var ue = UE.getEditor(element[0], {
						initialFrameHeight : '200',
						topOffset : 45,
						zIndex : 1029,
						initialContent : ''
					});
					scope.ue = ue
					element.on('destroyed', function() {
						ue.destroy()
					})
					if (ngModelCtrl) {
						ue.ready(function() {
							element.css('height', '0px')
							element.css('padding', '0px')
							element.css('display', 'block')
							element.css('resize', 'none')
							ue.setContent(current)
							ue.addListener('contentChange', function() {
								ngModelCtrl.$setViewValue(ue.getContent())
							})
						})
					}
				})
			}
		}
	}
	sc.directive('ueditor', UEditorDirective)
	sc.filter('toArray', function() {
		return function(obj) {
			if (!(obj instanceof Object))
				return obj;
			var arr = []
			angular.forEach(obj, function(v, k) {
				if (angular.isObject(v) || angular.isArray(v)) {
					v.$key = k
					arr.push(v)
				}
			})
			return arr;
		}
	});
	function UploadCtrl() {
		var ctrl = this
		this.init = function(server) {
			var dtd = $.Deferred();
			ctrl.server = server
			require([ 'Stream' ], function(Stream) {
				ctrl.stream = Stream
				dtd.resolve();
			})
			return dtd
		}
		this.create = function(config) {
			var cfg = {
				multipleFiles : true,
				maxSize : 104857600,
				tokenURL : ctrl.server + "/tk",
				uploadURL : "upload",
				swfURL : ctrl.server + "/asset/swf/FlashUploader.swf",
				frmUploadURL : "/fd",
				autoUploading : false,
				customered : true
			}
			angular.extend(cfg, config)
			return new ctrl.stream(cfg);
		}
		this.findFile = function(hash, size, files) {
			for ( var i in files) {
				var f = files[i]
				if (f.hash == hash && f.size == size) {
					return f;
				}
			}
		}
	}
	sc.controller('UploadCtrl', UploadCtrl)

	sc.run(function(modalService, $state, $stateParams, $rootScope, $http, pathPrefix) {
		$rootScope.$state = $state
		$rootScope.$stateParams = $stateParams
		$http.post(':sc:login/getLoginUrl').success(function(r) {
			$rootScope.$loginUrl = r
			if (!r) {
				location.href = pathPrefix + 'index.html'
			}
		})
		var navUtil = $rootScope.$nav = {}
		navUtil.jump = function(target) {
			$('html, body').animate({
				scrollTop : $('[anchor=' + target + ']').offset().top
			});
			navUtil.anchor = target
		}
		$rootScope.$state = $state
		var attachUtil = $rootScope.$attach = {}
		var serverQ = $http.post(':sc:attach/getServerWeb').success(function(r) {
			attachUtil.$server = r
			return r;
		})
		attachUtil.preview = function(attach) {
			$http.post(':sc:attach/resolvePreview', {
				hash : attach.hash,
				size : attach.size
			}).success(function(r) {
				var a = $('<a/>').attr("href", r).attr("target", "_blank");
				$(document.body).append(a);
				a[0].click();
				a.remove()
				// var w = window.open('_blank')
				// w.location = r
			})
		}
		attachUtil.getServerUrl = function() {
			return serverQ;
		}
		attachUtil.viewImage = function(attach) {
			var a = $('<a/>').attr("href", attachUtil.$server + '/preview/getImage?hash=' + attach.hash + '&size=' + attach.size).attr(
					"target", "_blank");
			$(document.body).append(a);
			a[0].click();
			a.remove()
		}
		attachUtil.download = function(attach) {
			delete attach.loadTime;
			$.ajax({
				url : pathPrefix + 'attach/resolveDownload',
				data : attach,
				type : 'POST',
				async : false
			}).then(function(r) {
				var form = $('<form></form>');
				form.attr('action', r);
				form.attr('method', 'post');
				form.attr('target', '_blank');
				$(document.body).append(form);
				form.submit();
				form.remove();
			})
		}
		attachUtil.getImageUrl = function(attach) {
			if (attachUtil.$server) {
				return attachUtil.$server + '/preview/getImage?hash=' + attach.hash + '&size=' + attach.size;
			}
		}
	})
	sc.filter('to_trusted', [ '$sce', function($sce) {
		return function(text) {
			return $sce.trustAsHtml(text);
		}
	} ]);
	function formFactory() {

	}
	sc.factory('formFactory', formFactory);
})()